<template>
  <div v-if="!initLoading">
    <el-dialog
      v-model="visible"
      title="售后审核"
      @before-ok="createOk(createRef)"
      @close="close(createRef)"
      width="800px"
      top="100px"
    >
      <el-form
        :model="createForm"
        :rules="createRules"
        ref="createRef"
        label-width="120px"
        size="default"
      >
        <div class="mb30" v-if="orderRefundDetail.type.value == 3">
          <el-alert title="提示" type="warning" :closable="false">
            <template #default>
              <div>
                该操作将执行订单原路退款
                并关闭当前售后单，请确认并填写退款的金额（不能大于订单实付款）
              </div>
              <div>
                注：当前订单存在后台改价记录，退款金额请参考订单实付款金额
              </div>
            </template>
          </el-alert>
        </div>

        <el-form-item label="商品信息：">
          <div class="flex">
            <el-avatar
              shape="square"
              :size="60"
              :src="orderRefundDetail.order_goods?.goods_image"
            ></el-avatar>
            <div class="ml10">
              <div class="te2">
                {{ orderRefundDetail.order_goods?.goods_name }}
              </div>
              <div class="mt5 flex">
                <span class="text-grey">规格:</span>
                <span>{{ orderRefundDetail.order_goods?.sku_attr_text }}</span>
                <span class="text-grey ml20">商品总额:</span>
                <money
                  :value="orderRefundDetail.order_goods?.total_pay_price"
                ></money>
                <span class="text-grey ml20">订单实付金额:</span>
                <money :value="orderRefundDetail.order.pay_price"></money>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="售后类型：">
          <el-tag type="" disable-transitions>{{
            orderRefundDetail.type.name
          }}</el-tag>
        </el-form-item>
        <el-form-item label="审核状态：" prop="is_agree">
          <el-radio-group v-model="createForm.is_agree">
            <el-radio :label="1" border>同意</el-radio>
            <el-radio :label="2" border>拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <template
          v-if="
            orderRefundDetail.type.value != 3 &&
            orderRefundDetail.delivery_type.value == 'express' &&
            createForm.is_agree == 1
          "
        >
          <el-form-item label="退货地址：" prop="address_id">
            <el-select
              v-model="createForm.address_id"
              placeholder="选择退货地址"
              class="form-select-fil"
            >
              <el-option
                v-for="item in refundAddressList"
                :key="item.id"
                :label="`${item.name},${item.phone},${item.detail}`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
        <template v-if="createForm.is_agree == 2">
          <el-form-item label="拒绝原因：" prop="refuse_desc">
            <el-input
              v-model="createForm.refuse_desc"
              :rows="4"
              type="textarea"
              placeholder="请输入拒绝原因"
            />
          </el-form-item>
        </template>
        <template
          v-if="orderRefundDetail.type.value == 3 && createForm.is_agree == 1"
        >
          <el-form-item label="退款金额：" prop="refund_money">
            <el-input
              v-model="createForm.refund_money"
              placeholder="请输入退款金额"
              type="number"
            />
            <help hideIcon>
              请输入退款金额，最多可退
              {{
                $utils.getArrayMin([
                  orderRefundDetail?.order.pay_price || 0,
                  orderRefundDetail?.order_goods?.total_pay_price || 0,
                ])
              }}
              元
            </help>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="flex center">
          <el-button @click="visible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="btnLoading"
            :disabled="btnLoading"
            @click="createOk(createRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  <script lang="ts">
export default {
  name: "storeOrderCancel",
};
</script>
<script lang="ts" setup>
import { ref, getCurrentInstance, nextTick, reactive } from "vue";
import type { FormInstance } from "element-plus";
import type { Result, ResultError } from "@/types";
import { getRefundAddressSelect } from "@/api/store/refund_address";
import {
  getOrderRefundDetail,
  auditOrderRefund,
} from "@/api/store/order_refund";

const {
  proxy: { $message, $utils },
} = getCurrentInstance() as any;

const emit = defineEmits(["success"]);

const visible = ref<boolean>(false);

const operationId = ref<number>(0);

const createRef = ref<typeof FormInstance>();

const btnLoading = ref<boolean>(false);

const initLoading = ref<boolean>(true);

const createForm = ref<any>({
  is_agree: 0,
  address_id: null,
  refuse_desc: "",
  refund_money: "",
});

const refundMoneyValid = (rule: any, value: any, callback: any) => {
  if (
    orderRefundDetail.value.type.value == 3 &&
    createForm.value.is_agree == 1
  ) {
    if (value == "") {
      callback(new Error("请输入退款金额"));
    }
    var _money = $utils.getArrayMin([
      orderRefundDetail.value?.order.pay_price || 0,
      orderRefundDetail.value?.order_goods?.total_pay_price || 0,
    ]);
    if (Number(value) < 0 || Number(value) > Number(_money)) {
      callback(new Error(`退款金额不能小于0，且不能大于${_money}`));
    }
    callback();
  } else {
    callback();
  }
};

const refundDescValid = (rule: any, value: any, callback: any) => {
  if (createForm.value.is_agree == 2 && value == "") {
    callback(new Error("拒绝原因不能为空！"));
  } else {
    callback();
  }
};

const addressValid = (rule: any, value: any, callback: any) => {
  if (orderRefundDetail.value.type.value == 2 && value == "") {
    callback(new Error("请选择退货地址"));
  } else {
    callback();
  }
};

const createRules: any = reactive({
  is_agree: [{ required: true, message: "请选择审核状态" }],
  address_id: [{ validator: addressValid }],
  refuse_desc: [{ validator: refundDescValid }],
  refund_money: [{ validator: refundMoneyValid }],
});

const orderRefundDetail = ref<any>({});

const toInit = () => {
  initLoading.value = true;
  getOrderRefundDetail({
    id: operationId.value,
  })
    .then((res: Result) => {
      orderRefundDetail.value = res.data;
      initLoading.value = false;
      if (
        orderRefundDetail.value.type.value != 3 &&
        orderRefundDetail.value.delivery_type.value == "express"
      ) {
        toInitRefundAddress();
      }
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const refundAddressList = ref<any>([]);

const toInitRefundAddress = () => {
  getRefundAddressSelect()
    .then((res: Result) => {
      refundAddressList.value = res.data;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const createOk = async (formEl: typeof FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid: any, fields: any) => {
    console.log(valid, fields);
    if (valid) {
      if (btnLoading.value) {
        return false;
      }
      btnLoading.value = true;
      auditOrderRefund({
        id: operationId.value,
        is_agree: createForm.value.is_agree,
        refuse_desc: createForm.value.refuse_desc,
        address_id: createForm.value.address_id,
        refund_money: createForm.value.refund_money,
      })
        .then((res: Result) => {
          $utils.successMsg(res);
          emit("success");
          close();
        })
        .catch((err: ResultError) => {
          $utils.errorMsg(err);
          close();
        });
    }
  });
};

const open = (id: number = 0) => {
  initLoading.value = true;
  if (id != 0) {
    operationId.value = id;
  }
  nextTick(() => {
    toInit();
  });
  visible.value = true;
};

const close = async (formEl: typeof FormInstance | undefined = undefined) => {
  if (formEl) {
    formEl.resetFields();
  }
  operationId.value = 0;
  btnLoading.value = false;
  visible.value = false;
};

defineExpose({ open });
</script>